<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <label for="guessNum">请猜一个数字：</label>
	<input type="text" id="guessNum" class="guessNum" />
	<input type="submit" name="" id="" value="确定" class="guessSubmit"/>
	<p class="guesses"></p>
	<p class="lastResult"></p>
	<p class="lowOrHi"></p>
	
	
<script type="text/javascript">
	let randomNumber = Math.floor(Math.random()* 100) + 1;
	
	const guesses = document.querySelector('.guesses');
	const lastResult = document.querySelector('.lastResult')
	const lowOrHi = document.querySelector('.lowOrHi')
	
	const guessSubmit = document.querySelector('.guessSubmit')
	const guessNum = document.querySelector('.guessNum')
	
	let guessCount = 1;
	let resetButton;
	function checkGuess(){
		let userGuess = Number(guessNum.value);
		if(guessCount === 1){
			guesses.textContent = '上次猜的数字：';
		}
		guesses.textContent += userGuess + ' '
		
		if(userGuess === randomNumber){
			lastResult.textContent = '恭喜你！猜对了';
			lastResult.style.backgroundColor = 'green';
			lowOrHi.textContent = '';
			setGameOver();
		}else if(guessCount === 10){
			lastResult.textContent = '答题次数过多，游戏结束！'
			setGameOver();
		}else{
			lastResult.textContent = '回答错误！';
			lastResult.style.backgroundColor = 'red';
			if(userGuess < randomNumber){
				lowOrHi.textContent = '猜低了！'
			}else if(userGuess > randomNumber){
				lowOrHi.textContent = '猜高了！'
			}
		}
		guessCount ++;
		guessNum.value = '';

		guessNum.focus();
		
	}
	
	guessSubmit.addEventListener('click',checkGuess);
	function setGameOver(){
		guessNum.disabled = true;
		guessSubmit.disabled = true;
		resetButton = document.createElement('button');
		resetButton.textContent = '开始新游戏！';
		document.body.appendChild(resetButton);
		resetButton.addEventListener('click',resetGame);
	}
	
	function resetGame(){
		guessCount = 1;
		const resetParas = document.querySelectorAll('.resultParas p');
		for(let i = 0; i < resetParas.length;i ++){
			resetParas[i].textContent = '';
		}
		resetButton.parentNode.removeChild(resetButton);
		
		guessNum.disabled = false;
		guessSubmit.disabled = false;
		guessNum.value = '';
		guessNum.focus();
		
		lastResult.style.backgroundColor = 'burlywood';
		
		randomNumber = Math.floor(Math.random() * 100) + 1;
	}
</script>
</body>
</html>